package com.szs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szs.common.R;
import com.szs.mapper.UserMapper;
import com.szs.pojo.User;
import com.szs.service.UserService;
import com.szs.util.SystemConstant;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @Override
    public R<User> login(Map map, HttpSession session) {

        // 获取用户手机号
        String phone = (String) map.get("phone");
        // 获取页面输入的验证码
        String code = (String) map.get("code");
        // 获取session中存入的验证码
        Object sessionCode = session.getAttribute(phone);
        // 判断输入的验证码是否相等
        if (sessionCode != null && sessionCode.equals(code)) {

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = this.getOne(queryWrapper);
            if (user == null) {
                // 如果是新用户，则自动注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(SystemConstant.STATUS_ON);
                this.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
